package com.alibaba.cirtus.ots.application.app.ability.facade.v2serviceimpl;

import com.alibaba.citrus.ots.common.util.DateUtils;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.QueryGoodsListRequest;
import com.epoch.app.bcorder.model.dto.QueryGoodsListResponse;
import com.epoch.app.bcorder.model.dto.SearchStoreTerminalForPullRequest;
import com.epoch.app.bcorder.model.dto.WarehouseInfo;
import com.epoch.app.bcorder.service.PlatformEnhanceService;
import com.epoch.app.bcorder.service.UnifiedInventoryService;
import com.epoch.app.otsapplicationappsdk.networkinventorylist.dto.AsyncRequest;
import com.epoch.app.otsapplicationappsdk.networkinventorylist.dto.PageQueryStoreInventoryRequest;
import com.epoch.app.otsapplicationappsdk.networkinventorylist.dto.PageQueryStoreInventoryResponse;
import com.epoch.app.otsapplicationappsdk.networkinventorylist.dto.RenderRequest;
import com.epoch.app.otsapplicationappsdk.networkinventorylist.service.NetworkInventoryListService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class NetworkInventoryListV2ServiceImpl implements NetworkInventoryListService {

    private static Log log = Log.getLogger(NetworkInventoryListV2ServiceImpl.class);

    private final static int PAGE_SIZE_500 = 500;

    @Autowired
    private UnifiedInventoryService unifiedInventoryService;

    @Autowired
    private PlatformEnhanceService platformEnhanceService;

    @Override
    public Object render(RenderRequest renderRequest) {
        JSONObject result = new JSONObject();
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(renderRequest.getAttr()));
        Integer pageSize = jsonObject.getInteger("pageSize");
        int limit = pageSize != null ? pageSize : 10;
        Integer currentPage = jsonObject.getInteger("currentPage");
        if (currentPage == null) {
            currentPage = 1;
        }
        int start = (currentPage - 1) * limit;
        try {
            PageQueryStoreInventoryRequest request = new PageQueryStoreInventoryRequest();
            request.setType(4);
            if (jsonObject.getString("warehouseId") != null) {
                request.setWarehouseIds(Arrays.asList(jsonObject.getString("warehouseId")));
            }
//            else {
//                request.setWarehouseIds(getDefaultStoreInfo());
//            }
            request.setStart(start);
            request.setLimit(limit);
            log.info("render_stockManageService.queryBusinessInventoryByPage$request:" + JSON.toJSONString(request));
            PageQueryStoreInventoryResponse response = pageQueryStoreInventory(request);
            //log.info("render_stockManageService.queryBusinessInventoryByPage$response:" + JSON.toJSONString(response));
            if (!response.getSuccess()){
                throw new Exception("调用门店库存接口失败");
            }
            JSONObject page = new JSONObject();
            page.put("pageSize", limit);
            page.put("currentPage", currentPage);
            page.put("total", response.getTotal());
            int totalPage = response.getTotal() / limit;
            if (response.getTotal()%limit>0){
                totalPage++;
            }
            page.put("totalPage", totalPage);
            if (currentPage>1){
                result.put("reload", false);
            }
            result.put("page", page);
            result.put("success",true);
            result.put("itemList",response.getResult());
            result.put("statistics",response.getStatistic());
        }catch (Exception e){
            result.put("success", false);
            result.put("msg",e.getMessage());
        }
        log.info("NetworkInventoryListServiceImpl_render_result={}", JSON.toJSONString(result));
        return result;
    }

    @Override
    public Object async(AsyncRequest asyncRequest) {
        Object requestBody = asyncRequest.getAttr();
        if (requestBody == null) {
            return null;
        }
        JSONObject result = new JSONObject();
        try {
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(requestBody));
            log.info("async_jsonObject" + JSON.toJSONString(jsonObject));
            PageQueryStoreInventoryRequest request = buildSyncRequest(jsonObject);
            //处理特殊时间格式
            buildDate(request);
            JSONObject fields = jsonObject.getJSONObject("fields");
            Integer currentPage = fields.getInteger("currentPage");
            Integer pageSize = fields.getInteger("pageSize");
            int limit = 10;
            if (pageSize != null) {
                limit = pageSize;
            }
            if (currentPage == null) {
                currentPage = 1;
            }
            int start = (currentPage - 1) * limit;
            request.setStart(start);
            request.setLimit(limit);
            log.info("pageQueryStoreInventory$request:" + JSON.toJSONString(request));
            PageQueryStoreInventoryResponse response = pageQueryStoreInventory(request);
            //log.info("pageQueryStoreInventory$response:" + JSON.toJSONString(response));
            if (!response.getSuccess()){
                throw new Exception("调用门店库存接口失败");
            }
            result.put("success", true);
            result.put("itemList", response.getResult());
            result.put("statistics",response.getStatistic());
            JSONObject page = new JSONObject();
            page.put("pageSize", request.getLimit());
            page.put("currentPage", currentPage);
            if (currentPage>1){
                result.put("reload", false);
            }
            page.put("total", response.getTotal());
            int totalPage = response.getTotal() / limit;
            if (response.getTotal()%limit>0){
                totalPage++;
            }
            page.put("totalPage", totalPage);
            result.put("page", page);
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        log.info("NetworkInventoryListServiceImpl_async_result={}", JSON.toJSONString(result));
        return result;
    }

    //处理生产日期格式 前时间组件直接点击确定勾选的是当前时间年月日时分秒 统一处理成 YY-MM-DD 00:00:00 不处理会导致查询数据有出入
    private void buildDate(PageQueryStoreInventoryRequest request) {
        try {
            if (request != null && CollectionUtils.isNotEmpty(request.getDom())) {
                List<String> dom = new ArrayList<>();
                for (Object obj : request.getDom()) {
                    if (StringUtils.isNotBlank(obj.toString())) {
                        String time = obj.toString().substring(0,11);
                        dom.add(time+"00:00:00");
                    }
                }
                request.setDom(dom);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //构建异步请求参数
    private PageQueryStoreInventoryRequest buildSyncRequest(JSONObject jsonObject) throws Exception{
        JSONObject fields = jsonObject.getJSONObject("fields");
        PageQueryStoreInventoryRequest request = new PageQueryStoreInventoryRequest();
        request.setType(4);
        //门店
        JSONArray array = fields.getJSONArray("selectOptions");
        enrichStoreParam(request, array);
        //货品
        String fuzzyName = fields.getString("value");
        enrichGoodsParam(request, fuzzyName);
        //筛选面板
        JSONObject filter = fields.getJSONObject("filterOptions");
        enrichBoardParam(request, filter);
        return request;
    }

    //添加门店ID参数
    private void enrichStoreParam(PageQueryStoreInventoryRequest request,JSONArray array) throws Exception{
        if (array!=null && array.size()>0) {
            JSONObject selected = array.getJSONObject(0).getJSONObject("selected");
            if (selected!=null && StringUtils.isNotBlank(selected.getString("value"))) {
                request.setWarehouseIds(Arrays.asList(selected.getString("value")));
            }
//            else {
//                request.setWarehouseIds(getDefaultStoreInfo());
//            }
        }
    }
    //添加商品ID参数
    private void enrichGoodsParam(PageQueryStoreInventoryRequest request,String fuzzyName){
        if (StringUtils.isNotBlank(fuzzyName)) {
            List<String> goodIds = getGoodsIdList(fuzzyName);
            request.setGoodsIds(goodIds);
        }
    }
    //添加筛选面板 销售组织、渠道、部门、客户
    private void enrichBoardParam(PageQueryStoreInventoryRequest request,JSONObject array){
        if (array==null || array.size()==0) {
            return;
        }
        JSONObject selected = array.getJSONObject("select");
        if (selected==null) {
            return;
        }
        String orgBussinessUnitCode = selected.getString("orgBussinessUnitCode");
        request.setOrgBussinessUnitCode(orgBussinessUnitCode);
        String orgSaleOrganizationCode = selected.getString("orgSaleOrganizationCode");
        request.setOrgSaleOrganizationCode(orgSaleOrganizationCode);
        String orgSaleChannelCode = selected.getString("orgSaleChannelCode");
        request.setOrgSaleChannelCode(orgSaleChannelCode);
        String orgSaleDepartmentCode = selected.getString("orgSaleDepartmentCode");
        request.setOrgSaleDepartmentCode(orgSaleDepartmentCode);
        JSONObject timer = selected.getJSONObject("timer");
        if (timer!=null){
            String startTime = timer.getString("startTime");
            String endTime = timer.getString("endTime");
            List<String> times = new ArrayList<>();
            times.add(StringUtils.isNotBlank(startTime)?DateUtils.stampToDate(startTime):"");
            times.add(StringUtils.isNotBlank(endTime)?DateUtils.stampToDate(endTime):"");
            request.setDom(times);
        }
    }

    private List<String> getGoodsIdList(String fuzzyName){
        List<String> result = new ArrayList<>();
        QueryGoodsListRequest request = new QueryGoodsListRequest();
        request.setTitle(fuzzyName);
        log.info("queryGoodsList_request" + JSON.toJSONString(request));
        Result<List<QueryGoodsListResponse>> queryGoodsListResponse = platformEnhanceService.queryGoodsList(request);
        if (!queryGoodsListResponse.isSuccess() || CollectionUtils.isEmpty(queryGoodsListResponse.getResult())){
            return result;
        }
        for (QueryGoodsListResponse response:queryGoodsListResponse.getResult()){
            JSONObject object = (JSONObject)JSON.toJSON(response);
            JSONArray jsonArray = object.getJSONArray("goodsList");
            if (jsonArray.isEmpty()){
                continue;
            }
            for (Object o : jsonArray){
                JSONObject good = (JSONObject)JSON.toJSON(o);
                result.add(good.getString("id"));
            }
        }
        return result;
    }

    //一次性拉取所有的门店
    private List<String> getDefaultStoreInfo() throws Exception{
        List<String> storeIds = new ArrayList<>();
        SearchStoreTerminalForPullRequest request = new SearchStoreTerminalForPullRequest();
        request.setModel(6);
        request.setStart(0);
        request.setLimit(PAGE_SIZE_500);
        log.info("searchStoreTerminalForPull$request:" + JSON.toJSONString(request));
        Result<List<WarehouseInfo>> response = unifiedInventoryService.searchStoreTerminalForPull(request);
        //log.info("unifiedInventoryService.wmsQueryStoreTerminalList$response:" + JSON.toJSONString(response));
        if (response == null || CollectionUtils.isEmpty(response.getResult())) {
            throw new Exception("未查到当前用户组织权限下的门店");
        }
        storeIds.addAll(response.getResult().stream().map(WarehouseInfo::getId).collect(Collectors.toList()));
        int totalCnt = response.getTotal();
        if (totalCnt>PAGE_SIZE_500) {
            int totalPage = totalCnt / PAGE_SIZE_500;
            if (totalCnt % PAGE_SIZE_500 > 0) {
                totalPage++;
            }
            for (int pageNo = 1; pageNo < totalPage; pageNo++) {
                request.setStart(pageNo * PAGE_SIZE_500);
                log.info("searchStoreTerminalForPull$request:" + JSON.toJSONString(request));
                response = unifiedInventoryService.searchStoreTerminalForPull(request);
                if (response != null && CollectionUtils.isNotEmpty(response.getResult())) {
                    storeIds.addAll(response.getResult().stream().map(WarehouseInfo::getId).collect(Collectors.toList()));
                }
            }
        }
        return storeIds;
    }
}
